from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt

from web import models
from web.forms.wiki import WikiModelForm 
from web.views import wiki
from utils.encrypt import uid
from utils.tencent.cos import upload_buffer_file

def wiki(request,project_id):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id:
        # objs = models.Wiki.objects.filter(project=request.tracer.project).all()
        return render(request,"web/wiki.html")
    else:
        # 显示文章内容
        wiki_obj= models.Wiki.objects.filter(id=wiki_id).first()
        wiki_editable = models.Wiki.objects.filter(id=wiki_id, user=request.tracer.user).first()
        return render(request,'web/wiki.html',{'wiki_obj':wiki_obj,'wiki_editable':wiki_editable})

def wiki_add(request, project_id):
    if request.method == "GET":
        objs_add = WikiModelForm(request)
        context = {
            'forms':objs_add
        }
        return render(request, 'web/wiki.html',context)
    else:
        objs_add = WikiModelForm(request, data=request.POST)
        if objs_add.is_valid():
            objs_add.instance.project = request.tracer.project
            objs_add.instance.user = request.tracer.user
            parent_obj= objs_add.cleaned_data.get('parent')
            if not parent_obj:
                objs_add.instance.depth = 1
            else:
                parent_depth = models.Wiki.objects.filter(id = parent_obj.id).first().depth
                objs_add.instance.depth = parent_depth +1
            # print(objs)
            wiki_obj = objs_add.save()
            base_url = reverse('web:wiki', kwargs={'project_id':project_id})
            url = '{0}?wiki_id={1}'.format(base_url,wiki_obj.id)
            return redirect(url)
            # return render(request,'web/wiki.html')
        return render(request, 'web/wiki.html',{'forms':objs_add})

def wiki_catalog(request, project_id):
    objs = models.Wiki.objects.filter(project=request.tracer.project).order_by('depth','id').values('id','title','parent')
    
    context = {
        'status':True,
        'objs':list(objs)
    }
    # print(context)
    return JsonResponse(context)

def remove_children(all_items, delete_list):
    if not delete_list:
        return all_items
    new_delete_list=[]
    new_all_items=[]
    for delete in delete_list:
        # 必须倒序all_item[::-1]
        for item in all_items[::-1]:
            if delete==item[2]:
                # 把item的child放入new_delete_list
                new_delete_list.append(item[0])
            if item[0]==delete:
                all_items.remove(item)
            else:
                print('views/wiky/remove_children:delete wiki_id=%d'%item[0])
                pass
    return remove_children(all_items,new_delete_list)


def get_all_delete_list(all_items, delete_list, all_delete_list):
    if not delete_list:
        return 
    new_delete_list=[]
    new_all_items=[]
    for delete in delete_list:
        for item in all_items:
            if delete==item[2]:
                all_delete_list.append(item[0])
                new_delete_list.append(item[0])
    get_all_delete_list(all_items,new_delete_list,all_delete_list)
    
    
    
def get_choices(wiki_id, project):
    # choices_list=[(1,'xx'),(2,'xxx')]        
    # obj = models.Wiki.objects.filter(id=wiki_id).first()
    # children_wiki_items = obj.children.values_list('id','title','parent_id')
    # 从自己开始delete
    delete_list=[wiki_id]
    # for item in children_wiki_items:
    #     delete_list.append(item[0])
    wiki_proj_items = models.Wiki.objects.filter(project=project).values_list('id','title','parent_id')
    
    choices_list = remove_children(list(wiki_proj_items), delete_list)
    
    # # another func to remove 
    # # all_delete_list=[wiki_id,]
    # # get_all_delete_list(wiki_proj_items,delete_list,all_delete_list)
    # # remove parent_id
    choices_list = [(x,y) for x,y,z in choices_list]
    total_list = [('','请选择'),]
    total_list.extend(choices_list)
    # print(total_list)
    return total_list
        

def wiki_edit(request, project_id,wiki_id):
    obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    if not obj:
        url = reverse('web:wiki', kwargs={'project_id': project_id}) 
        return redirect(url)
    if request.method == "GET":
        # instance 可以赋初始值
        objs_edit = WikiModelForm(request, instance=obj)

        # 表单初始值
        ## from django.forms.models import model_to_dict
        ## obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
        ## objs_edit.initial= model_to_dict(obj,fields=['title','content','parent'])
        # 去除wiki_id的子文件，防止死循环
        total_list = get_choices(wiki_id, request.tracer.project)
        objs_edit.fields['parent'].choices = total_list
        context = {
            'forms':objs_edit
        }
        
        return render(request,'web/wiki.html',context)
    else:
        objs_edit = WikiModelForm(request, data=request.POST)
        if objs_edit.is_valid():
            objs_edit.instance.project = request.tracer.project
            # print(objs)
            # objs.save()
            obj = models.Wiki.objects.filter(id=wiki_id).first()
            parent_obj = objs_edit.cleaned_data.get('parent')
            if not parent_obj:
                objs_edit.cleaned_data['depth'] = 1
            else:
                parent_depth = models.Wiki.objects.filter(id = parent_obj.id).first().depth
                objs_edit.cleaned_data['depth'] = parent_depth + 1
            
            update_depth(obj, objs_edit.cleaned_data['depth'])
            # update wiki
            models.Wiki.objects.filter(id=wiki_id).update(**objs_edit.cleaned_data)
            base_url = reverse('web:wiki', kwargs={'project_id':project_id})
            url = '{0}?wiki_id={1}'.format(base_url,wiki_id)
            return redirect(url)
            # return render(request,'web/wiki.html')
        return render(request, 'web/wiki.html',{'forms':objs_edit})   #显示错误信息

def update_depth(obj, offset):
    obj.depth = offset  # can be deleted
    models.Wiki.objects.filter(id=obj.id).update(depth=offset)
    print("update, id=%d, parent=%d, depth=%d"%(obj.id, obj.parent_id if obj.parent_id else 0 ,obj.depth))
    children_objs = obj.children.all()
    if not children_objs:
        # 递归出口
        return
    else:
        # children_objs = obj.children.all()
        for  child_obj in children_objs:
            update_depth(child_obj, offset+1)
        
  
def wiki_delete(request, project_id,wiki_id):
    obj = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    if not obj:
        url = reverse('web:wiki', kwargs={'project_id': project_id}) 
        return redirect(url)
    all_delete_list=[wiki_id,]
    delete_list=[wiki_id,]
    wiki_proj_items = models.Wiki.objects.filter(project_id=project_id).values_list('id','title','parent_id')
    get_all_delete_list(list(wiki_proj_items), delete_list, all_delete_list)
    # 批量删除
    print('views/wiki/wiki_delete:%s'%all_delete_list)
    obj = models.Wiki.objects.filter(id__in=all_delete_list).delete()
    return render(request,'web/wiki.html')

@csrf_exempt
def wiki_upload(request, project_id):
    # 返回result可以通知markdown图片上传结果，result的格式是固定的。
    result = {
        'success':0,
        'url':None,
        'message':None
    }
    image_body = request.FILES.get('editormd-image-file')
    if not image_body:
        result['message']="文件不存在"
    ext = image_body.name.rsplit('.')[-1]
    Key = "{}.{}".format(uid(request.tracer.user.mobile_phone),ext)
    region = 'ap-beijing'
    bucket = request.tracer.project.bucket
    url = upload_buffer_file(bucket,region,image_body,Key)
    result['success']=1
    result['url']=url

    return JsonResponse(result)